{% extends "pc/template.html" %}

{% block title %}
版本列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .container-xxl { padding: 2rem 1.5rem; }
    .card { margin: 1rem 0; border: none; border-radius: 1rem; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); transition: all 0.3s ease; }
    .card:hover { box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.1); }
    .card-header { background: #fff; border-bottom: 1px solid rgba(0,0,0,0.05); padding: 1.5rem; border-radius: 1rem 1rem 0 0 !important; }
    .card-header h5 { color: #566a7f; font-weight: 600; margin: 0; }
    .btn-primary { background: #696cff; border-color: #696cff; padding: 0.5rem 1rem; font-weight: 500; transition: all 0.2s ease; }
    .btn-primary:hover { background: #5f61e6; border-color: #5f61e6; transform: translateY(-1px); }
    .table-responsive { margin: 0; padding: 1rem; }
    .table { margin: 0; }
    .table thead th { background: #f8f9fa; color: #566a7f; font-weight: 600; border-bottom: 2px solid #e9ecef; padding: 1rem; }
    .table tbody td { padding: 1rem; vertical-align: middle; color: #697a8d; border-bottom: 1px solid #e9ecef; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .table tbody tr { transition: all 0.2s ease; }
    .table tbody tr:hover { background: #f8f9fa; }
    .action-buttons .btn { padding: 0.4rem 0.6rem; margin: 0 0.2rem; border-radius: 0.5rem; transition: all 0.2s ease; }
    .action-buttons .btn:hover { transform: translateY(-2px); }
    .dropdown-menu { border: none; border-radius: 0.5rem; box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15); padding: 0.5rem; min-width: 160px; }
    .dropdown-item { padding: 0.6rem 1rem; color: #697a8d; border-radius: 0.4rem; display: flex; align-items: center; gap: 0.5rem; transition: all 0.2s ease; }
    .dropdown-item:hover { background: #f8f9fa; color: #566a7f; }
    .dropdown-item.view { color: #03c3ec; }
    .dropdown-item.edit { color: #ffab00; }
    .dropdown-item.delete { color: #ff3e1d; }
    .dropdown-item.view:hover { background: rgba(3,195,236,0.1); }
    .dropdown-item.edit:hover { background: rgba(255,171,0,0.1); }
    .dropdown-item.delete:hover { background: rgba(255,62,29,0.1); }
    .dropdown-toggle::after { display: none; }
    .action-btn { background: #f8f9fa; border: 1px solid #d9dee3; color: #697a8d; padding: 0.4rem 0.8rem; border-radius: 0.5rem; display: flex; align-items: center; gap: 0.5rem; transition: all 0.2s ease; }
    .action-btn:hover { background: #f5f5f9; border-color: #d9dee3; color: #566a7f; }
    .action-btn i { font-size: 1.1rem; }
    .pagination { margin: 1rem 0 0 0; justify-content: center; }
    .pagination .page-link { padding: 0.5rem 0.75rem; color: #566a7f; background-color: #fff; border: 1px solid #d9dee3; margin: 0 0.2rem; border-radius: 0.5rem; transition: all 0.2s ease; }
    .pagination .page-item.active .page-link { background-color: #696cff; border-color: #696cff; color: #fff; }
    .pagination .page-link:hover { color: #696cff; background-color: #f5f5f9; border-color: #d9dee3; transform: translateY(-1px); }
    .pagination .page-item.disabled .page-link { color: #a3a4cc; pointer-events: none; background-color: #fff; border-color: #d9dee3; }
    @media (max-width: 768px) { .container-xxl { padding: 1rem; } .card-header { padding: 1rem; } .table-responsive { padding: 0.5rem; } .action-buttons .btn { padding: 0.3rem 0.5rem; margin: 0 0.1rem; } }
    /* 调整SweetAlert2的z-index，确保其高于Bootstrap模态框 */
    .swal2-container {
        z-index: 9999 !important;
    }
    .swal2-popup {
        z-index: 9999 !important;
    }
    .swal2-backdrop-show {
        z-index: 9998 !important;
    }
    /* 确保模态框的z-index低于SweetAlert2 */
    .modal {
        z-index: 1050;
    }
    .modal-backdrop {
        z-index: 1040;
    }
    /* 版本分类标签溢出处理 */
    .version-type-badge {
        max-width: 220px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
        cursor: pointer;
        position: relative;
        margin-right: 8px;
        margin-bottom: 6px;
    }
    /* 分类区滚动条 */
    #addedVersionTypes {
        max-height: 200px;
        overflow-y: auto;
        padding-right: 4px;
    }
    /* 版本详情内容自动换行且不溢出 */
    .version-detail-wrap {
        word-break: break-all;
        white-space: pre-line;
        overflow-wrap: break-word;
        max-width: 100%;
    }
    /* 版本详情图片区域横向滚动 */
    .version-image-list {
        display: flex;
        gap: 10px;
        overflow-x: auto;
        padding-bottom: 6px;
        margin-bottom: 8px;
    }
    .version-image-thumb {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 6px;
        cursor: pointer;
        border: 1px solid #eee;
        transition: box-shadow 0.2s;
    }
    .version-image-thumb:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
    /* 预览大图弹窗 */
    .version-image-preview-modal .modal-dialog {
        max-width: 90vw;
    }
    .version-image-preview-modal .modal-content {
        background: rgba(0,0,0,0.95);
        color: #fff;
        border: none;
        border-radius: 1rem;
        text-align: center;
    }
    .version-image-preview-modal img {
        max-width: 80vw;
        max-height: 70vh;
        margin: 0 auto;
        display: block;
    }
    .version-image-preview-nav {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
    }
    .version-image-preview-nav button {
        background: rgba(255,255,255,0.2);
        border: none;
        border-radius: 50%;
        width: 2.5rem;
        height: 2.5rem;
        color: #fff;
        font-size: 1.5rem;
        cursor: pointer;
        transition: background 0.2s;
    }
    .version-image-preview-nav button:hover {
        background: rgba(255,255,255,0.4);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">版本列表</h5>
            <button type="button" class="btn btn-primary" onclick="showAddVersionModal()">
                <i class="bx bx-plus"></i> 添加版本
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>版本号</th>
                            <th>描述</th>
                            <th>下载地址</th>
                            <th>发布者</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="versionTableBody">
                        <!-- 版本数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加/编辑版本模态框 -->
    <div class="modal fade" id="versionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="versionModalTitle">添加版本</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="versionForm">
                        <input type="hidden" id="versionId">
                        <input type="hidden" id="version_publisher_id" name="version_publisher">
                        <div class="mb-3">
                            <label class="form-label" for="version_number">版本号</label>
                            <input type="text" class="form-control" id="version_number" name="version_number" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="version_description">描述</label>
                            <textarea class="form-control" id="version_description" name="version_description" rows="2" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="version_download_url">下载地址</label>
                            <input type="url" class="form-control" id="version_download_url" name="version_download_url">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="version_publisher">发布者</label>
                            <input type="text" class="form-control" id="version_publisher" value="{{ request.session.user.username }}" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="version_status">状态</label>
                            <select class="form-control" id="version_status" name="version_status">
                                <option value="1">正常</option>
                                <option value="2">下架</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="versionModalSaveBtn" onclick="saveVersion()">保存</button>
                    <button type="button" class="btn btn-info" id="manageVersionTypeBtn" style="margin-left:8px;" onclick="openManageVersionType()">管理分类</button>
                    <button type="button" class="btn btn-secondary" id="manageVersionImageBtn" style="margin-left:8px;" onclick="openManageVersionImage()">管理图片</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看版本详情模态框 -->
    <div class="modal fade" id="viewVersionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">版本详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">版本号</label>
                        <p id="viewVersionNumber" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <p id="viewVersionDescription" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">下载地址</label>
                        <p id="viewVersionDownloadUrl" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">发布者</label>
                        <p id="viewVersionPublisher" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">状态</label>
                        <p id="viewVersionStatus" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">创建时间</label>
                        <p id="viewVersionCreateTime" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">更新时间</label>
                        <p id="viewVersionUpdateTime" class="form-control-static version-detail-wrap"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">版本分类</label>
                        <div id="viewVersionTypeList"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">版本图片</label>
                        <div class="version-image-list" id="viewVersionImageList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 版本分类模态框 -->
    <div class="modal fade" id="versionTypeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加版本分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="versionTypeForm" onsubmit="return false;">
                        <input type="hidden" id="versionTypeVersionId" name="version">
                        <div class="mb-3">
                            <label class="form-label" for="version_update_type">更新类型</label>
                            <select class="form-control" id="version_update_type" name="version_update_type" required>
                                <option value="1">新增</option>
                                <option value="2">优化</option>
                                <option value="3">修复</option>
                                <option value="4">删除</option>
                                <option value="100">其他</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="version_update_description">更新说明</label>
                            <textarea class="form-control" id="version_update_description" name="version_update_description" rows="3" required></textarea>
                        </div>
                    </form>
                    <div class="mb-3">
                        <label class="form-label">已添加分类</label>
                        <div id="addedVersionTypes" class="d-flex flex-wrap gap-2"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addVersionTypeToList()">保存</button>
                    <button type="button" class="btn btn-success" onclick="submitAllVersionTypes()">完成</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 版本图片上传模态框 -->
    <div class="modal fade" id="versionImageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传版本图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="versionImageVersionId">
                    <div class="mb-3">
                        <label class="form-label">选择图片（可多选）</label>
                        <input type="file" class="form-control" id="versionImageFiles" multiple accept="image/*">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">已上传图片</label>
                        <div id="versionImagePreview" class="d-flex flex-wrap gap-2"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="uploadVersionImages()">上传</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    let allVersions = [];
    let currentPage = 1;
    const itemsPerPage = 10;
    let currentEditVersionId = '';

    document.addEventListener('DOMContentLoaded', function() {
        getVersionList();
    });

    function getVersionList() {
        const loadingToast = Swal.fire({ title: '加载中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        axios.get('/api/version/get_version_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allVersions = response.data.data;
                    currentPage = 1;
                    renderVersionTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取版本列表失败', 'error');
            })
            .finally(function() { loadingToast.close(); });
    }

    function renderVersionTable() {
        const tbody = document.getElementById('versionTableBody');
        tbody.innerHTML = '';
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageVersions = allVersions.slice(startIndex, endIndex);
        currentPageVersions.forEach(version => {
            const tr = document.createElement('tr');
            // 状态颜色
            let statusColor = 'secondary';
            let statusText = '未知';
            if (version.version_status === 1 || version.version_status === '正常') {
                statusColor = 'success';
                statusText = '正常';
            } else if (version.version_status === 2 || version.version_status === '维护') {
                statusColor = 'warning';
                statusText = '维护';
            }
            tr.innerHTML = `
                <td>${version.version_id || version.id || ''}</td>
                <td title="${version.version_number}">${version.version_number}</td>
                <td title="${version.version_description}">${version.version_description}</td>
                <td title="${version.version_download_url}"><a href="${version.version_download_url}" target="_blank">${version.version_download_url}</a></td>
                <td>${version.version_publisher || '-'}</td>
                <td><span class="badge bg-${statusColor}">${statusText}</span></td>
                <td class="action-buttons">
                    <div class="dropdown">
                        <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-dots-vertical-rounded"></i>
                            <span>操作</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item view" href="#" onclick="viewVersion('${version.version_id || version.id}')">
                                    <i class="bx bx-show"></i><span>查看</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item edit" href="#" onclick="editVersion('${version.version_id || version.id}')">
                                    <i class="bx bx-edit"></i><span>编辑</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item delete" href="#" onclick="deleteVersion('${version.version_id || version.id}')">
                                    <i class="bx bx-trash"></i><span>删除</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(allVersions.length / itemsPerPage);
        let paginationHTML = '';
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;
        pagination.innerHTML = paginationHTML;
    }

    function changePage(page) {
        if (page < 1 || page > Math.ceil(allVersions.length / itemsPerPage)) return;
        currentPage = page;
        renderVersionTable();
        renderPagination();
    }

    function showAddVersionModal() {
        document.getElementById('versionModalTitle').textContent = '添加版本';
        document.getElementById('versionForm').reset();
        document.getElementById('versionId').value = '';
        document.getElementById('version_publisher_id').value = '{{ request.session.user.id }}';
        document.getElementById('versionModalSaveBtn').onclick = saveVersion;
        const modal = new bootstrap.Modal(document.getElementById('versionModal'));
        modal.show();
    }

    // 版本分类本地暂存
    let versionTypeList = [];
    // 分类类型颜色映射
    const versionTypeColorMap = {
        1: 'success', // 新增-绿色
        2: 'primary', // 优化-蓝色
        3: 'warning', // 修复-橙色
        4: 'danger',  // 删除-红色
        100: 'secondary', // 其他-灰色
        '新增': 'success',
        '优化': 'primary',
        '修复': 'warning',
        '删除': 'danger',
        '其他': 'secondary'
    };
    const versionTypeTextMap = {
        1: '新增', 2: '优化', 3: '修复', 4: '删除', 100: '其他'
    };

    function showVersionTypeModal(versionId) {
        document.getElementById('versionTypeVersionId').value = versionId;
        versionTypeList = [];
        renderAddedVersionTypes();
        document.getElementById('versionTypeForm').reset();
        const versionTypeModal = new bootstrap.Modal(document.getElementById('versionTypeModal'));
        versionTypeModal.show();
    }

    // 保存单个分类到本地
    function addVersionTypeToList() {
        const version = document.getElementById('versionTypeVersionId').value;
        const type = document.getElementById('version_update_type').value;
        const desc = document.getElementById('version_update_description').value.trim();
        if (!type || !desc) {
            Swal.fire('错误', '请选择类型并填写说明', 'error');
            return;
        }
        versionTypeList.push({ version, version_update_type: type, version_update_description: desc });
        renderAddedVersionTypes();
        document.getElementById('versionTypeForm').reset();
    }

    // 渲染已添加分类
    function renderAddedVersionTypes() {
        const container = document.getElementById('addedVersionTypes');
        container.innerHTML = '';
        versionTypeList.forEach((item, idx) => {
            const badge = document.createElement('span');
            badge.className = `badge bg-${versionTypeColorMap[item.version_update_type]} px-3 py-2 version-type-badge`;
            badge.title = `${versionTypeTextMap[item.version_update_type]}：${item.version_update_description}`;
            badge.innerHTML = `${versionTypeTextMap[item.version_update_type]}：${item.version_update_description} <a href="#" onclick="removeVersionType(${idx})" style="color:white;margin-left:8px;"><i class='bx bx-x'></i></a>`;
            container.appendChild(badge);
        });
    }

    // 移除某个分类
    function removeVersionType(idx) {
        versionTypeList.splice(idx, 1);
        renderAddedVersionTypes();
    }

    // 版本图片相关
    let currentVersionImageId = '';
    function showVersionImageModal(versionId) {
        document.getElementById('versionImageVersionId').value = versionId;
        document.getElementById('versionImageFiles').value = '';
        loadVersionImages(versionId);
        const modal = new bootstrap.Modal(document.getElementById('versionImageModal'));
        modal.show();
    }
    // 加载已上传图片
    function loadVersionImages(versionId) {
        axios.get(`/api/version/get_version/${versionId}/`).then(res => {
            if (res.data.code === 200) {
                // 假设后端返回有 images 字段，否则需单独接口
                if (res.data.data.images) {
                    renderVersionImagePreview(res.data.data.images);
                } else {
                    // 兼容无 images 字段
                    document.getElementById('versionImagePreview').innerHTML = '<span class="text-muted">暂无图片</span>';
                }
            }
        });
    }
    // 渲染图片缩略图
    function renderVersionImagePreview(images) {
        const container = document.getElementById('versionImagePreview');
        if (!images || images.length === 0) {
            container.innerHTML = '<span class="text-muted">暂无图片</span>';
            return;
        }
        container.innerHTML = '';
        images.forEach(img => {
            const div = document.createElement('div');
            div.className = 'position-relative';
            div.style.width = '80px';
            div.style.height = '80px';
            div.innerHTML = `
                <img src="${img.image}" alt="版本图片" style="width:100%;height:100%;object-fit:cover;border-radius:6px;">
                <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" onclick="deleteVersionImage('${img.id}')"><i class='bx bx-x'></i></button>
            `;
            container.appendChild(div);
        });
    }
    // 上传图片
    function uploadVersionImages() {
        const versionId = document.getElementById('versionImageVersionId').value;
        const files = document.getElementById('versionImageFiles').files;
        if (!files.length) {
            Swal.fire('提示', '请选择图片', 'info');
            return;
        }
        const loadingToast = Swal.fire({ title: '上传中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        const uploadPromises = Array.from(files).map(file => {
            const formData = new FormData();
            formData.append('image', file);
            return axios.post(`/api/version/upload_version_image/${versionId}/`, formData);
        });
        Promise.all(uploadPromises).then(() => {
            Swal.fire({ icon: 'success', title: '成功', text: '图片上传成功', showConfirmButton: false, timer: 1500 });
            loadVersionImages(versionId);
        }).catch(() => {
            Swal.fire('错误', '图片上传失败', 'error');
        }).finally(() => { loadingToast.close(); });
    }
    // 删除图片
    function deleteVersionImage(imageId) {
        Swal.fire({ title: '确认删除', text: '确定要删除这张图片吗？', icon: 'warning', showCancelButton: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then((result) => {
            if (result.isConfirmed) {
                axios.delete(`/api/version/delete_version_image/${imageId}/`).then(res => {
                    if (res.data.code === 200) {
                        Swal.fire({ icon: 'success', title: '成功', text: '图片删除成功', showConfirmButton: false, timer: 1000 });
                        // 重新加载图片
                        const versionId = document.getElementById('versionImageVersionId').value;
                        loadVersionImages(versionId);
                    } else {
                        Swal.fire('错误', res.data.msg, 'error');
                    }
                });
            }
        });
    }
    // 修改submitAllVersionTypes，分类完成后弹出图片上传
    function submitAllVersionTypes() {
        if (versionTypeList.length === 0) {
            Swal.fire('提示', '请至少添加一个分类', 'info');
            return;
        }
        const loadingToast = Swal.fire({ title: '保存中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        const versionId = document.getElementById('versionTypeVersionId').value;
        Promise.all(versionTypeList.map(item => {
            const formData = new FormData();
            formData.append('version', item.version);
            formData.append('version_update_type', item.version_update_type);
            formData.append('version_update_description', item.version_update_description);
            return axios.post('/api/version/create_version_type/', formData);
        })).then(() => {
            Swal.fire({ icon: 'success', title: '成功', text: '所有分类添加成功', showConfirmButton: false, timer: 1000 });
            const versionTypeModal = bootstrap.Modal.getInstance(document.getElementById('versionTypeModal'));
            versionTypeModal.hide();
            versionTypeList = [];
            // 分类完成后弹出图片上传
            setTimeout(() => { showVersionImageModal(versionId); }, 500);
        }).catch(() => {
            Swal.fire('错误', '添加分类失败', 'error');
        }).finally(() => { loadingToast.close(); });
    }

    function saveVersion() {
        const form = document.getElementById('versionForm');
        const formData = new FormData(form);
        const versionId = document.getElementById('versionId').value;
        const isEdit = !!versionId;
        const url = isEdit ? `/api/version/update_version/${versionId}/` : '/api/version/create_version/';
        const loadingToast = Swal.fire({ title: isEdit ? '保存中...' : '添加中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        axios.post(url, formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({ icon: 'success', title: '成功', text: isEdit ? '版本信息更新成功' : '版本添加成功', showConfirmButton: false, timer: 1500 }).then(() => { 
                        getVersionList();
                        if (!isEdit) {
                            showVersionTypeModal(response.data.data.version_id);
                        }
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', isEdit ? '更新版本失败' : '添加版本失败', 'error');
            })
            .finally(function() { loadingToast.close(); });
        const versionModal = bootstrap.Modal.getInstance(document.getElementById('versionModal'));
        versionModal.hide();
    }

    function viewVersion(versionId) {
        const loadingToast = Swal.fire({ title: '加载中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        axios.get(`/api/version/get_version/${versionId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const v = response.data.data;
                    document.getElementById('viewVersionNumber').textContent = v.version_number;
                    document.getElementById('viewVersionDescription').textContent = v.version_description;
                    document.getElementById('viewVersionDownloadUrl').textContent = v.version_download_url;
                    document.getElementById('viewVersionPublisher').textContent = v.version_publisher;
                    document.getElementById('viewVersionStatus').textContent = v.version_status === 2 ? '维护' : '正常';
                    document.getElementById('viewVersionCreateTime').textContent = v.create_time || '';
                    document.getElementById('viewVersionUpdateTime').textContent = v.update_time || '';
                    // 分类渲染
                    const typeList = v.version_type || [];
                    const typeListDiv = document.getElementById('viewVersionTypeList');
                    typeListDiv.innerHTML = '';
                    if (typeList.length > 0) {
                        typeList.forEach(item => {
                            const badge = document.createElement('span');
                            const color = versionTypeColorMap[item.version_update_type] || 'secondary';
                            badge.className = `badge bg-${color} version-type-badge`;
                            badge.title = `${item.version_update_type}：${item.version_update_description}`;
                            badge.innerText = `${item.version_update_type}：${item.version_update_description}`;
                            typeListDiv.appendChild(badge);
                        });
                    } else {
                        typeListDiv.innerHTML = '<span class="text-muted">暂无分类</span>';
                    }
                    // 图片渲染
                    const imageList = v.version_image || [];
                    const imageListDiv = document.getElementById('viewVersionImageList');
                    imageListDiv.innerHTML = '';
                    if (imageList.length > 0) {
                        imageList.forEach((img, idx) => {
                            const imgElem = document.createElement('img');
                            imgElem.src = img.image;
                            imgElem.className = 'version-image-thumb';
                            imgElem.alt = '版本图片';
                            imgElem.onclick = function() { openVersionImagePreview(imageList.map(i=>i.image), idx); };
                            imageListDiv.appendChild(imgElem);
                        });
                    } else {
                        imageListDiv.innerHTML = '<span class="text-muted">暂无图片</span>';
                    }
                    const modal = new bootstrap.Modal(document.getElementById('viewVersionModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取版本详情失败', 'error');
            })
            .finally(function() { loadingToast.close(); });
    }

    function editVersion(versionId) {
        const loadingToast = Swal.fire({ title: '加载中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        axios.get(`/api/version/get_version/${versionId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const v = response.data.data;
                    document.getElementById('versionModalTitle').textContent = '编辑版本';
                    document.getElementById('versionId').value = v.version_id || v.id;
                    document.getElementById('version_number').value = v.version_number;
                    document.getElementById('version_description').value = v.version_description;
                    document.getElementById('version_download_url').value = v.version_download_url;
                    document.getElementById('version_publisher').value = v.version_publisher;
                    document.getElementById('version_publisher_id').value = '{{ request.session.user.id }}';
                    document.getElementById('version_status').value = v.version_status === '维护' ? 2 : 1;
                    document.getElementById('versionModalSaveBtn').onclick = saveVersion;
                    currentEditVersionId = v.version_id || v.id;
                    const modal = new bootstrap.Modal(document.getElementById('versionModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取版本信息失败', 'error');
            })
            .finally(function() { loadingToast.close(); });
    }

    // 编辑弹窗中管理分类
    function openManageVersionType() {
        if (!currentEditVersionId) return;
        showVersionTypeModal(currentEditVersionId);
    }
    // 编辑弹窗中管理图片
    function openManageVersionImage() {
        if (!currentEditVersionId) return;
        showVersionImageModal(currentEditVersionId);
    }

    function deleteVersion(versionId) {
        Swal.fire({ title: '确认删除', text: '确定要删除这个版本吗？', icon: 'warning', showCancelButton: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({ title: '删除中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
                axios.delete(`/api/version/delete_version/${versionId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({ icon: 'success', title: '成功', text: '版本删除成功', showConfirmButton: false, timer: 1500 }).then(() => { getVersionList(); });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除版本失败', 'error');
                    })
                    .finally(function() { loadingToast.close(); });
            }
        });
    }

    // 版本图片大图预览
    let versionImagePreviewList = [];
    let versionImagePreviewIndex = 0;
    function openVersionImagePreview(imgList, idx) {
        versionImagePreviewList = imgList;
        versionImagePreviewIndex = idx;
        renderVersionImagePreviewModal();
        const modal = new bootstrap.Modal(document.getElementById('versionImagePreviewModal'));
        modal.show();
    }
    function renderVersionImagePreviewModal() {
        const img = document.getElementById('versionImagePreviewImg');
        img.src = versionImagePreviewList[versionImagePreviewIndex];
        document.getElementById('versionImagePreviewCounter').textContent = `${versionImagePreviewIndex+1} / ${versionImagePreviewList.length}`;
        document.getElementById('versionImagePreviewPrev').disabled = versionImagePreviewIndex === 0;
        document.getElementById('versionImagePreviewNext').disabled = versionImagePreviewIndex === versionImagePreviewList.length-1;
    }
    function versionImagePreviewPrev() {
        if (versionImagePreviewIndex > 0) {
            versionImagePreviewIndex--;
            renderVersionImagePreviewModal();
        }
    }
    function versionImagePreviewNext() {
        if (versionImagePreviewIndex < versionImagePreviewList.length-1) {
            versionImagePreviewIndex++;
            renderVersionImagePreviewModal();
        }
    }
</script>
<!-- 版本图片大图预览模态框 -->
<div class="modal fade version-image-preview-modal" id="versionImagePreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <img id="versionImagePreviewImg" src="" alt="预览图片">
                <div class="version-image-preview-nav mt-2">
                    <button id="versionImagePreviewPrev" onclick="versionImagePreviewPrev()"><i class="bx bx-chevron-left"></i></button>
                    <span id="versionImagePreviewCounter"></span>
                    <button id="versionImagePreviewNext" onclick="versionImagePreviewNext()"><i class="bx bx-chevron-right"></i></button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}